using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;

namespace AjaxControlToolkit
{
	public class ScriptBase : Control, IScriptControl
	{
		#region Protected methods

		/// <summary>
		/// Fires the PreRender event
		/// </summary>
		/// <param name="e"></param>
		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);

			ScriptManager.RegisterScriptControl(this);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="writer"></param>
		protected override void Render(HtmlTextWriter writer)
		{
			base.Render(writer);

			Page.VerifyRenderingInServerForm(this);

			if (!DesignMode)
				ScriptManager.RegisterScriptDescriptors(this);
		}

		#endregion

		#region Private methods

		/// <summary>
		/// Ensures a ScriptManager exists on the Page for this Control
		/// </summary>
		private void EnsureScriptManager()
		{
			if (_scriptManager == null)
			{
				_scriptManager = ScriptManager.GetCurrent(Page);
				if (_scriptManager == null)
				{
					throw new HttpException(Resources.E_NoScriptManager);
				}
			}
		}

		#endregion

		#region Public properties

		/// <summary>
		/// 
		/// </summary>
		public string Path
		{
			get { return (string)(ViewState["Path"] ?? string.Empty); }
			set { ViewState["Path"] = value; }
		}

		#endregion

		#region Protected properties

		/// <summary>
		/// Gets the ScriptManager for the page
		/// </summary>
		protected ScriptManager ScriptManager
		{
			get
			{
				EnsureScriptManager();
				return _scriptManager;
			}
		}

		#endregion

		#region Private fields

		/// <summary>
		/// 
		/// </summary>
		private ScriptManager _scriptManager;

		#endregion

		#region Implementation of IScriptControl

		/// <summary>
		/// Gets a collection of script descriptors that represent ECMAScript (JavaScript) client components.
		/// </summary>
		/// <returns>
		/// An <see cref="T:System.Collections.IEnumerable" /> collection of <see cref="T:System.Web.UI.ScriptDescriptor" /> objects.
		/// </returns>
		public IEnumerable<ScriptDescriptor> GetScriptDescriptors()
		{
			return null;
		}

		/// <summary>
		/// Gets a collection of <see cref="T:System.Web.UI.ScriptReference" /> objects that define script resources that the control requires.
		/// </summary>
		/// <returns>
		/// An <see cref="T:System.Collections.IEnumerable" /> collection of <see cref="T:System.Web.UI.ScriptReference" /> objects.
		/// </returns>
		public IEnumerable<ScriptReference> GetScriptReferences()
		{
			if (!Visible) return null;

			var refs = new List<ScriptReference>();
			refs.AddRange(ScriptObjectBuilder.GetScriptReferences(GetType()));
			if (Path.Length > 0)
				refs.Add(new ScriptReference(Path));

			return refs;
		}

		#endregion

	}
}